<?php
/**
 * Created by PhpStorm.
 * User: hisheng
 * Date: 2017/6/7
 * Time: 19:11
 */
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use App\Banner;


class BannerController extends Controller
{
    public $banner;
    
    public function __construct(Banner $banner)
    {
        $this->banner = $banner ;
    }
    
    public function index(){
        $banners = $this->banner->orderBy('created_at','desc')->where('is_delete',0)->get();
        return view('admin.banner.index',compact('banners'));
    }
    
    public function add(){
        return view('admin.banner.add');
    }
    
    public function postAdd(){
        $id = Input::get('id');
        if($id){
            $banner = $this->banner->find($id);
            if($banner){
                $this->banner = $banner ;
            }
            
        }
        $this->insertDefault('url');
        $this->insertDefault('type');
        $this->insertFile('image');
        if($this->banner->image){
            $this->banner->save();
            return redirect('/admin/banners');
        }
        return $this->error('缺少image');
    }
    
    public function insertDefault($name){
        $v = Input::get($name);
        if($name){
            $this->banner->$name = $v;
        }
    }
    public function insertFile($name){
        $avatar = $this->saveFile($name);
        if($avatar){
            $this->banner->image = $avatar;
        }
    }
    
    public function edit($id){
        $banner = $this->banner->find($id);
        if($banner){
            return view('admin.banner.edit',compact('banner'));
        }
        return $this->error('参数错误');
    }
    
    public function delete($id){
        $banner = $this->banner->find($id);
        $banner->is_delete = 1;
        $banner->save();
        return redirect('/admin/banners');
    }
    
    public function top($id){
        $banner = $this->banner->find($id);
        if($banner){
            $banner->created_at = date('Y-m-d H:i:s');
            $banner->save();
        }
        return redirect('/admin/banners');
    }
    
    
    
    
}
